#!/usr/bin/env python3
# -*- coding: utf-8 -*-

# Copyright (c) 2024 Song Yan 843558935@qq.com. All rights reserved.
# This code is licensed under the GPL-2.0+ license. See LICENSE file in the project root for full license information.


import logging
import os
import re

logger = logging.getLogger(__name__)


def replace_dbpath(content):
    pattern = r'^%_dbpath\t.*'
    replacement = r'%_dbpath\t\t%{_usr}/lib/sysimage/rpm'

    updated_content = re.sub(pattern, replacement, content, flags=re.MULTILINE)
    return updated_content

def manage_rpmdb_symlinks():
    if os.path.isdir("/var/lib/rpm"):
        with open("/var/lib/rpm/.migratedb", "w"):
            pass
    if not os.path.isdir("/var/lib/rpm") and os.path.isdir("/usr/lib/sysimage/rpm") and not os.path.isfile("/usr/lib/sysimage/rpm/.rpmdbdirsymlink_created"):
        os.symlink("/usr/lib/sysimage/rpm", "/var/lib/rpm")
        with open("/usr/lib/sysimage/rpm/.rpmdbdirsymlink_created", "w"):
            pass

def safe_run_command(ctx, command, env_vars=None):
    """
    安全地执行命令，避免注入攻击。
    
    参数:
    - ctx: 上下文对象，用于执行命令。
    - command: 要执行的命令，作为列表。
    - env_vars: 环境变量字典。
    
    返回值:
    - 无
    """
    if env_vars is None:
        env_vars = {"LC_ALL": "C", "LANG": "en_US.UTF-8"}

    result = ctx.run(command, warn=True, pty=False, hide=True, env=env_vars)
    if result.return_code != 0:
        logger.debug("Failed to execute command: %s" % command)
        logger.debug("Command output: %s" % result.stdout)
        logger.debug("Command error output: %s" % result.stderr)
    else:
        logger.debug("Command executed successfully: %s" % command)
    return result
        